CODE 33. Same Tree

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/20/2013-09-20-CODE 33 Same Tree/

访问原文「CODE 33. Same Tree

Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
return dfs(p, q);
}
boolean dfs(TreeNode left, TreeNode right) {
if ((null != left && null == right) || (null == left)
&& (null != right)) {
return false;
} else if (left == null && right == null) {
return true;
} else if (left.val != right.val) {
return false;
}
boolean leftResult = dfs(left.left, right.left);
boolean rightResult = dfs(left.right, right.right);
return (leftResult && rightResult) ? true : false;
}
Jerky Lu wechat
欢迎加入微信公众号